<?php
App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');

class UsersController extends AppController {
    
    function index(){
        $this->loadModel('Usert');
        $todos = $this->User->find('all', array(
            'joins' => array(
                array('table' => 'tipos_usuario',
                    'alias'=>'Tipo',
                    'type' => 'INNER',
                    'conditions' => array(
                        'User.tipo = Tipo.id'
                    )
                )
            ),
            'fields'=>array(
                'User.id','User.nombre','User.correo',
                'User.usuario','User.tipo','Tipo.nombre'
            )
        ));
        for($i=0;$i<count($todos);$i++){
            $todos[$i]['User']['tipo']=$todos[$i]['Tipo']['nombre'];
            $todos[$i]=$todos[$i]['User'];
            
        }
        $this->set(array('todos' => $todos, '_serialize' => 'todos'));
    }
    
    public function agregarUsuario() {
        $error = null;
        $this->loadModel('Usert');
        if($this->request->is('post')) {
            $user = $this->request->data;
            $users = $this->User->find('all', array('conditions' => array('usuario' => $user['usuario'])));
            if(count($users) === 0) {
                $tipo = $this->Usert->find('first', array(
                    'conditions' => array('Usert.nombre' => $user['tipo']),
                    'fields'=>array('Usert.id'),
                    ));
                $user['tipo']=$tipo['Usert']['id'];
                $user['pass'] = $this->RandomString(8);
                $user['status'] = 1;
                try {
                    $this->User->save($user);
                    $user['id']=$this->User->ultimoId();
                    $Email = new CakeEmail();
                    $Email->config('gmail');
                    $Email->from(array('onnneri@gmail.com' => 'Revsal'));
                    $Email->to($user['correo']);
                    $Email->subject("Registro Revsal");
                    $Email->send("Le damos la mas nada!!!. ".$user['usuario'].". \n
                        Su contraseña actual es la siguiente:\n\nContraseña: ".$user['pass']."\n");
                    unset($user['pass']);
                    $user['tipo']=$this->request->data['tipo'];
                    $error = false;
                    $this->set(array('user' => $user, '_serialize' => 'user'));
                    $this->viewClass = 'Json';
                } catch(PDOException $e) {
                    $error = true;
                }
            }
            else {
                $error = true;
            }
        }
        $this->set('error', $error);
    }
    public function RandomString($length=10,$uc=TRUE,$n=TRUE,$sc=FALSE)
    {
        $source = 'abcdefghijklmnopqrstuvwxyz';
        if($uc==1) $source .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        if($n==1) $source .= '1234567890';
        if($sc==1) $source .= '|@#~$%()=^*+[]{}-_';
        if($length>0){
            $rstr = "";
            $source = str_split($source,1);
            mt_srand((double)microtime() * 1000000);
            for($i=1; $i<=$length; $i++){
                $num = mt_rand(1,count($source));
                $rstr .= $source[$num-1];
            }
        }
        return $rstr;
    }
    
    public function cambiarContra() {
        
        $error = null;
        if($this->request->is('post')) {
            $user = $this->Auth->user();
            $user = $this->User->find('all', array('conditions' => array('id' => $user['id'])));
            if($user[0]['User']['pass'] == $this->User->hashea($this->request->data['Pass']['antiguo'])) {
                $user = array('User' => $this->Auth->user());
                $user['User']['pass'] = Security::hash($this->request->data['Pass']['nuevo'], NULL, true);
                try {
                    $this->User->save($user);
                    $error = false;
                } catch(PDOException $e) {
                    $error = true;
                }
            }
            else {
                $error = true;
            }
        }
        $this->set('error', $error);
    }
    
    function modificarUsuario(){
        $this->loadModel('Usert');
        if($this->request->is('post')) {
            try{
                
                $this->User->id = $_POST['id'];
                $user['nombre'] = $_POST['nombre'];
                $user['usuario'] = $_POST['usuario'];
                $user['correo'] = $_POST['correo'];
                $user['tipo'] = $this->Usert->find('first', array(
                    'conditions' => array('Usert.nombre' => $_POST['tipo']),
                    'fields'=>array('Usert.id'),
                ));
                $user['tipo']=$user['tipo']['Usert']['id'];
//                var_dump($user);
//                die;
                $this->User->save($user);
                $this->viewClass = 'Json';
            }
            catch(PDOException $e) {
                $error = true;
            }
            $error = null;
            
        }
        $this->set('error', $error);
        
    }
    function eliminarUsuario(){
        if($this->request->is('post')) {
            $id = $_POST['datos'][0];
            if(count($id)!=0){
                try{
                    $this->User->id = $id;
                    $this->User->delete();
                }
                catch(PDOException $e) {
                    $error = true;
                }
            }
            else
                $error = false;
            $error = null;
            $this->set('error', $error);
            $this->viewClass = 'Json';
        }
    }
    function obtenFecha(){
        $fecha = date('Y-m-d');
        $this->set(array('fecha' => $fecha, '_serialize' => 'fecha'));
        $this->viewClass = 'Json'; 
    }
//    function agregarUsuario(){
//  //      $this->loadModel('Usuario');
//        $user = array('usuario'=>$_POST['datos'][1],
//                        'clave'=>$_POST['datos'][2],
//                        'nombre'=>$_POST['datos'][3],
//                        'tipo'=>$_POST['datos'][4]);
//        $this->User->save($user);
//        $user['id']=$this->User->ultimoId();
//        $this->set(array('user' => $user, '_serialize' => 'user'));
//        $this->viewClass = 'Json';
//    }
    
    
    
    
    
    
    
    
}